// API配置文件
const BASE_URL = 'http://localhost:9204';

// API接口配置
const API_CONFIG = {
  // 用户相关接口
  USER: {
    LOGIN: '/mobile/user/login',
    INFO: '/mobile/user/info',
    LOGOUT: '/mobile/user/logout',
    REFRESH: '/mobile/user/refresh'
  },
  
  // 服务相关接口
  SERVICE: {
    LIST: '/mobile/service',
    DETAIL: '/mobile/service/',
    BY_MERCHANT: '/mobile/service/merchant/',
    BY_TYPE: '/mobile/service/type/',
    SEARCH: '/mobile/service/search',
    POPULAR: '/mobile/service/popular',
    PRICE_RANGE: '/mobile/service/price-range'
  }
};

// 通用请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = uni.getStorageSync('access_token');
    
    // 设置请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    };
    
    // 如果有token，添加到请求头
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }
    
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: header,
      success: (res) => {
        // 直接返回响应数据，让调用方处理业务逻辑
        resolve(res.data);
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(err);
      }
    });
  });
};

// 用户API
const userApi = {
  // 用户登录
  login(data) {
    return request({
      url: API_CONFIG.USER.LOGIN,
      method: 'POST',
      data: data
    });
  },
  
  // 获取用户信息
  getUserInfo() {
    return request({
      url: API_CONFIG.USER.INFO,
      method: 'GET'
    });
  },
  
  // 用户退出
  logout() {
    return request({
      url: API_CONFIG.USER.LOGOUT,
      method: 'POST'
    });
  },
  
  // 刷新token
  refreshToken() {
    return request({
      url: API_CONFIG.USER.REFRESH,
      method: 'POST'
    });
  }
};

// 服务API
const serviceApi = {
  // 获取服务列表
  getServiceList(params) {
    return request({
      url: API_CONFIG.SERVICE.SEARCH,
      method: 'GET',
      data: params
    });
  },
  
  // 获取服务详情
  getServiceDetail(id) {
    return request({
      url: API_CONFIG.SERVICE.DETAIL + id,
      method: 'GET'
    });
  },
  
  // 根据商户获取服务
  getServicesByMerchant(merchantId) {
    return request({
      url: API_CONFIG.SERVICE.BY_MERCHANT + merchantId,
      method: 'GET'
    });
  },
  
  // 获取热门服务
  getPopularServices(limit = 10) {
    return request({
      url: API_CONFIG.SERVICE.POPULAR,
      method: 'GET',
      data: { limit }
    });
  }
};

// 导出API
export {
  BASE_URL,
  API_CONFIG,
  request,
  userApi,
  serviceApi
};
